<template>
  <div class="page-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>活动管理</span>
        </div>
      </template>
      <el-table
        :data="promotions"
        style="width: 100%"
        border
        class="promotion-table"
        stripe
        height="100%"
      >
        <el-table-column prop="name" label="活动名称" min-width="150" />
        <el-table-column prop="type" label="活动类型" width="100">
          <template #default="scope">
            {{ formatPromotionType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatPromotionStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openAddItemDialog(scope.row)">添加商品</el-button>
            <el-button size="small" type="danger" @click="openItemListDialog(scope.row)">查看/删除商品</el-button>
            <el-button size="small" type="warning" @click="openConfigDialog(scope.row)">编辑配置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="fetchPromotions"
        class="pagination"
      />
    </el-card>

    <el-dialog
      title="编辑活动配置"
      v-model="configDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="100px">
        <el-form-item label="满减门槛" prop="threshold" v-if="currentPromotion.type === 3">
          <el-input v-model.number="configForm.threshold" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="折扣金额" prop="discount" v-if="currentPromotion.type === 3">
          <el-input v-model.number="configForm.discount" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="套餐价格" prop="comboPrice" v-if="currentPromotion.type === 4">
          <el-input v-model.number="configForm.comboPrice" type="number" min="0"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitConfig">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="添加商品到活动"
      v-model="itemDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="itemForm" :rules="itemRules" ref="itemFormRef" label-width="100px">
        <el-form-item label="选择商品" prop="skuId">
          <el-select v-model="itemForm.skuId" placeholder="请选择SKU" @change="updateSkuInfo">
            <el-option v-for="item in skus" :key="item.id" :label="item.spuTitle + ' - ' + item.specsJson" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="itemDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitItem">添加</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="活动商品列表"
      v-model="itemListDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-table :data="currentPromotionItems" style="width: 100%" border stripe>
        <el-table-column prop="skuId" label="商品ID" width="100" />
        <el-table-column prop="spuTitle" label="商品名称" min-width="150">
          <template #default="scope">
            {{ scope.row.spuTitle + ' - ' + scope.row.specsJson }}
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="满减门槛" width="120" v-if="currentPromotion.type === 3" />
        <el-table-column prop="discount" label="折扣金额" width="120" v-if="currentPromotion.type === 3" />
        <el-table-column prop="comboPrice" label="套餐价格" width="120" v-if="currentPromotion.type === 4" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="danger" @click="deleteItem(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="itemListDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getPromotionsService, getSkusServiceByAd, addFullReductionItemService, addComboItemService, getPromotionItemsService, deletePromotionItemService, updateConfigService } from '@/api/merchant'
import { useUserInfoStore } from '@/stores/userInfo'

const userInfoStore = useUserInfoStore()
const promotions = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const itemDialogVisible = ref(false)
const itemListDialogVisible = ref(false)
const currentPromotion = ref({})
const currentPromotionItems = ref([])
const skus = ref([])
const selectedSku = ref(null)
const configDialogVisible = ref(false)

const configForm = reactive({
  threshold: 0,
  discount: 0,
  comboPrice: 0
})

const configRules = reactive({
  threshold: [
    { required: true, message: '请输入满减门槛', trigger: 'blur', type: 'number' },
    { type: 'number', min: 0.01, message: '满减门槛必须大于0', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请输入折扣金额', trigger: 'blur', type: 'number' },
    { type: 'number', min: 0.01, message: '折扣金额必须大于0', trigger: 'blur' }
  ],
  comboPrice: [
    { required: true, message: '请输入套餐价格', trigger: 'blur', type: 'number' },
    { type: 'number', min: 0.01, message: '套餐价格必须大于0', trigger: 'blur' }
  ]
})

const itemForm = reactive({
  skuId: null
})

const itemRules = reactive({
  skuId: [{ required: true, message: '请选择商品', trigger: 'change' }]
})

const itemFormRef = ref(null)
const configFormRef = ref(null)

const fetchPromotions = async () => {
  try {
    const res = await getPromotionsService({ page: currentPage.value, size: pageSize.value })
    // 只保留满减（type=3）和套餐（type=4）的活动
    promotions.value = res.data.data.records.filter(item => [3, 4].includes(item.type))
    total.value = promotions.value.length // 更新总数
  } catch (error) {
    ElMessage.error('获取活动列表失败')
  }
}

const fetchSkus = async () => {
  try {
    const res = await getSkusServiceByAd()
    skus.value = res.data.data
  } catch (error) {
    ElMessage.error('获取SKU列表失败')
  }
}

const updateSkuInfo = (skuId) => {
  selectedSku.value = skus.value.find(sku => sku.id === skuId) || null
}

const fetchPromotionItems = async (promotion) => {
  try {
    const res = await getPromotionItemsService(promotion.id, promotion.type)
    currentPromotionItems.value = res.data.data
  } catch (error) {
    ElMessage.error('获取活动商品列表失败')
  }
}

const openAddItemDialog = (row) => {
  currentPromotion.value = row
  Object.assign(itemForm, {
    skuId: null
  })
  selectedSku.value = null
  nextTick(() => {
    itemFormRef.value?.resetFields()
  })
  itemDialogVisible.value = true
  fetchSkus()
}

const openConfigDialog = (row) => {
  currentPromotion.value = row
  Object.assign(configForm, {
    threshold: row.threshold || 0,
    discount: row.discount || 0,
    comboPrice: row.comboPrice || 0
  })
  nextTick(() => {
    configFormRef.value?.resetFields()
  })
  configDialogVisible.value = true
}

const openItemListDialog = (row) => {
  currentPromotion.value = row
  itemListDialogVisible.value = true
  fetchPromotionItems(row)
}

const submitItem = () => {
  itemFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const payload = { activityId: currentPromotion.value.id, skuId: itemForm.skuId }
        if (currentPromotion.value.type === 3) {
          await addFullReductionItemService(payload)
        } else if (currentPromotion.value.type === 4) {
          await addComboItemService(currentPromotion.value.id, itemForm.skuId)
        }
        ElMessage.success('添加商品成功')
        itemDialogVisible.value = false
        fetchPromotions()
      } catch (error) {
        ElMessage.error('添加商品失败')
      }
    }
  })
}

const submitConfig = () => {
  configFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const payload = {
          activityId: currentPromotion.value.id,
          threshold: currentPromotion.value.type === 3 ? configForm.threshold : null,
          discount: currentPromotion.value.type === 3 ? configForm.discount : null,
          comboPrice: currentPromotion.value.type === 4 ? configForm.comboPrice : null
        }
        await updateConfigService(payload)
        ElMessage.success('更新配置成功')
        configDialogVisible.value = false
        fetchPromotions()
      } catch (error) {
        ElMessage.error('更新配置失败')
      }
    }
  })
}

const deleteItem = async (row) => {
  try {
    await deletePromotionItemService(currentPromotion.value.id, row.skuId, currentPromotion.value.type)
    ElMessage.success('删除商品成功')
    fetchPromotionItems(currentPromotion.value)
  } catch (error) {
    ElMessage.error('删除商品失败')
  }
}

const formatPromotionType = (type) => {
  switch (type) {
    case 3: return '满减'
    case 4: return '套餐'
    default: return '-'
  }
}

const formatPromotionStatus = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已结束'
    default: return '-'
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'info'
    default: return ''
  }
}

fetchPromotions()
</script>

<style lang="scss" scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.box-card {
  margin: 0;
  padding: 12px;
  border-radius: 8px;
  box-shadow: var(--shadow);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  padding: 10px 12px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.promotion-table {
  flex: 1;
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 10px 12px;
  background-color: var(--card-bg);
}
</style>